package com.controller;

import com.aliyuncs.exceptions.ClientException;
import com.constant.RedisMessageConstant;
import com.entity.Result;
import com.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Random;

@RequestMapping("/SendCode")
@RestController
public class SendCodeController {
    @Autowired
    JedisPool jedisPool;
    /*发送预约验证码*/
    @RequestMapping("/order")
    public Result order(String telephone){
        /*校验手机号是否正确*/
        if (telephone==null||"".equals(telephone)){
            return new Result(false,"手机号不能为空");
        }
        String s = "^[1][3578]\\d{9}$";
        boolean b = telephone.matches(s);
        if (!b){
            return new Result(false,"手机号输入格式错误");
        }
        /*随机生成四位数*/
        Integer i = (int) (Math.random() * 9000) + 1000;
        Result result=null;
        try {
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,i.toString());
            System.out.println("发送的验证码是:"+i);
            /*吧验证码存储到缓存中*/
            jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,300,i.toString());
            result=new Result(true,"短信发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            result=new Result(false,"短信发送失败");
        }
        return result;
    }
    //发送快速登录验证码
    @RequestMapping("/send4Login")
    public Result login(String telephone){
        /*校验手机号是否正确*/
        if (telephone==null||"".equals(telephone)){
            return new Result(false,"手机号不能为空");
        }
        String s = "^[1][3578]\\d{9}$";
        boolean b = telephone.matches(s);
        if (!b){
            return new Result(false,"手机号输入格式错误");
        }
        //开始生成随机验证码
        Integer i=(int)(Math.random()*900000) +100000;
        //开始发送
        Result result=null;
        try {
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,i.toString());
            System.out.println(i);
            //保存到redis中
            jedisPool.getResource().setex(telephone+RedisMessageConstant.SENDTYPE_LOGIN,300,i.toString());
            result=new Result(true,"短信发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            result=new Result(false,"短信发送失败");
        }
        return result;

    }
}
